<template>
  <a-modal
    :open="open"
    title="编辑排序"
    @ok="handleOk"
    @cancel="handleCancel"

    :confirmLoading="loading"
  >
    <div class="sort-edit-form">
      <a-form :model="formData" style="padding:20px" layout="vertical">
        <a-form-item label="排序值" required>
          <a-input-number
            v-model:value="formData.sort"
            :min="0"
            :max="9999"
            placeholder="请输入排序值"
            style="width: 100%"
          />
        </a-form-item>
        <div class="sort-tip">
          <p>💡 排序值越小，题目在考试中显示越靠前</p>
          <p>💡 建议使用连续的排序值（1, 2, 3...）</p>
        </div>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:open', 'success']);

const loading = ref(false);
const formData = reactive({
  sort: 0
});

// 监听记录变化，更新表单数据
watch(() => props.record, (newRecord) => {
  if (newRecord && newRecord.id) {
    formData.sort = newRecord.sort || 0;
  }
}, { immediate: true });

// 确认保存
const handleOk = async () => {
  try {
    loading.value = true;
    
    // 验证排序值
    if (formData.sort < 0) {
      createMessage.warning('排序值不能为负数');
      return;
    }
    
    // 触发保存事件
    emit('success', {
      id: props.record.id,
      sort: formData.sort
    });
    
    // 关闭模态框
    emit('update:open', false);
    createMessage.success(`排序已更新为: ${formData.sort}`);
    
  } catch (error) {
    console.error('保存排序失败:', error);
    createMessage.error('保存失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 取消编辑
const handleCancel = () => {
  emit('update:open', false);
};
</script>

<style lang="less" scoped>
.sort-edit-form {
  padding: 16px 0;
}

.sort-tip {
  margin-top: 16px;
  padding: 12px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  
  p {
    margin: 4px 0;
    color: #52c41a;
    font-size: 13px;
  }
}
</style>
